/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ucuenca.ec.nosql.IngresoDatos;

import edu.ucuenca.ec.nosql.testing.*;
import edu.ucuenca.ec.nosql.controller.util.TipoNodo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.neo4j.cypher.ExecutionEngine;
import org.neo4j.cypher.ExecutionResult;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
//import org.neo4j.graphdb.factory.HighlyAvailableGraphDatabaseFactory;
import org.neo4j.kernel.impl.util.StringLogger;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Farfan
 */
public class Face {

    private static final String NooDB = "/opt/neo4j-enterprise-2.2.0-M03";
    private static final String Prop = "/opt/neo4j-enterprise-2.2.0-M03/conf/neo4j.properties";
    Node first;
    Node second;
    Relationship relation;
    static GraphDatabaseService graphDatabaseservice;

    private static enum RelTypes implements RelationshipType {

        KNOWS,
        AMIGOS
    }

    public static void main(String[] args) {
        File archivo = null;
        FileReader fr = null;
        BufferedReader br = null;

    //   GraphDatabaseBuilder builder = new HighlyAvailableGraphDatabaseFactory()
        //        .newEmbeddedDatabaseBuilder(NooDB);
        GraphDatabaseFactory dbFactory = new GraphDatabaseFactory();
        graphDatabaseservice = dbFactory.newEmbeddedDatabase("/Users/mivkys/Documents/test");

       // GraphDatabaseBuilder builder = new HighlyAvailableGraphDatabaseFactory()
        //.newEmbeddedDatabaseBuilder(NooDB).loadPropertiesFromFile(Prop);
        //graphDatabaseservice = new GraphDatabaseFactory().newEmbeddedDatabase(NooDB);
        System.out.println("propiedades");

        //graphDatabaseservice = builder.newGraphDatabase();
        System.out.println("Base");

        Node principal, amigo = null, amigoDelAmigo;
        Relationship relacion;

        try {
            Transaction transaction = graphDatabaseservice.beginTx();
            try {
                principal = graphDatabaseservice.createNode(TipoNodo.USUARIO);
                principal.setProperty("Id", 0);
                principal.setProperty("nombres", "User0");
                principal.setProperty("pass", "1234");
                transaction.success();
            } finally {
                transaction.finish();
            }
            List<String> valores = new ArrayList();
            archivo = new File("/Users/mivkys/Documents/DataSets/facebook/0.edges");
            fr = new FileReader(archivo);
            br = new BufferedReader(fr);

            // Lectura del fichero
            String linea, us;

            while ((linea = br.readLine()) != null) {
                boolean p = true;
                StringTokenizer tokens = new StringTokenizer(linea);
                while (tokens.hasMoreTokens()) {
                    us = tokens.nextToken();
                    if (valores.contains(us)) {
                        System.out.println(us + "se repite" + valores.size());
                        transaction = graphDatabaseservice.beginTx();
                        try {
                            if (p) {
                                amigo = buscar(Integer.valueOf(us));
                                relacion = principal.createRelationshipTo(amigo, RelTypes.AMIGOS);
                                relacion.setProperty("Id",Integer.valueOf(us));
                                transaction.success();
                            } else {
                                amigoDelAmigo = buscar(Integer.valueOf(us));
                                relacion = amigo.createRelationshipTo(amigoDelAmigo, RelTypes.AMIGOS);
                                relacion.setProperty("Id", Integer.valueOf(us));
                                transaction.success();
                            }

                        } finally {
                            transaction.finish();
                        }
                    } else {
                        valores.add(us);
                        transaction = graphDatabaseservice.beginTx();
                        try {
                            if (p) {
                                amigo = graphDatabaseservice.createNode(TipoNodo.USUARIO);
                                amigo.setProperty("Id", Integer.valueOf(us));
                                amigo.setProperty("nombres", "User" + us);
                                amigo.setProperty("pass", "1234");
                                relacion = principal.createRelationshipTo(amigo, RelTypes.AMIGOS);
                                relacion.setProperty("Id", Integer.valueOf(us));
                                transaction.success();
                            } else {
                                amigoDelAmigo = graphDatabaseservice.createNode(TipoNodo.USUARIO);
                                amigoDelAmigo.setProperty("Id", Integer.valueOf(us));
                                amigoDelAmigo.setProperty("nombres", "User" + us);
                                amigoDelAmigo.setProperty("pass", "1234");
                                relacion = amigo.createRelationshipTo(amigoDelAmigo, RelTypes.AMIGOS);
                                relacion.setProperty("Id", Integer.valueOf(us));
                                transaction.success();
                            }

                        } finally {
                            transaction.finish();
                        }
                    }
                    //System.out.println(tokens.nextToken()+p);
                    p = false;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                if (null != fr) {
                    fr.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
//        HelloWorld hello=new HelloWorld();
//        hello.createDataBase();
//        //hello.removeDatabase();
        graphDatabaseservice.shutdown();
        System.out.println("Noe DataBase apagada");
    }

    public static Node buscar(int parametro) {
        ExecutionEngine engine;
        engine = new ExecutionEngine(graphDatabaseservice, StringLogger.SYSTEM);

        String query = "match (n {Id: " + parametro + "}) return n";

        ExecutionResult result = engine.execute(query);

        scala.collection.Iterator<Node> it = result.columnAs("n");

        while (it.hasNext()) {

            Node n = it.next();
            System.out.println(n.getProperty("Id"));
            return n;

        }

        return null;
    }

}
